<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="6" v-for="stat in stats" :key="stat.title">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: stat.color }">
              <el-icon :size="24"><component :is="stat.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-title">{{ stat.title }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :xs="24" :sm="24" :md="16">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最近活动</span>
            </div>
          </template>
          <el-timeline>
            <el-timeline-item
              v-for="activity in activities"
              :key="activity.id"
              :timestamp="activity.time"
              placement="top"
            >
              <el-card>
                <h4>{{ activity.title }}</h4>
                <p>{{ activity.content }}</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="24" :md="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>快捷操作</span>
            </div>
          </template>
          <div class="quick-actions">
            <el-button
              v-for="action in quickActions"
              :key="action.label"
              :type="action.type"
              :icon="action.icon"
              class="action-button"
              @click="handleQuickAction(action)"
            >
              {{ action.label }}
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useNotificationStore } from '@/stores/notification'
import { getMemberList } from '@/api/members'
import { getMemberLevelList } from '@/api/memberLevels'
import { getMyNotificationList } from '@/api/notifications'
import {
  User,
  Document,
  Message,
  DataAnalysis
} from '@element-plus/icons-vue'

interface Stat {
  title: string
  value: number | string
  icon: any
  color: string
}

interface Activity {
  id: string | number
  title: string
  content: string
  time: string
}

interface QuickAction {
  label: string
  type: string
  icon: string
  action: string
}

const router = useRouter()
const authStore = useAuthStore()
const notificationStore = useNotificationStore()

const stats = ref<Stat[]>([
  { title: '会员数量', value: 0, icon: User, color: '#409eff' },
  { title: '会员等级', value: 0, icon: Document, color: '#67c23a' },
  { title: '未读通知', value: 0, icon: Message, color: '#e6a23c' },
  { title: '我的信息', value: '', icon: DataAnalysis, color: '#f56c6c' }
])

const activities = ref<Activity[]>([])

const quickActions = ref<QuickAction[]>([
  { label: '新增会员', type: 'primary', icon: 'Plus', action: 'toMembers' },
  { label: '管理等级', type: 'success', icon: 'Trophy', action: 'toMemberLevels' },
  { label: '个人中心', type: 'info', icon: 'User', action: 'toProfile' }
])

const handleQuickAction = (action: QuickAction): void => {
  switch (action.action) {
    case 'toMembers':
      router.push({ name: 'Members' })
      break
    case 'toMemberLevels':
      router.push({ name: 'MemberLevels' })
      break
    case 'toProfile':
      router.push({ name: 'Profile' })
      break
  }
}

// 加载统计数据
const loadStats = async (): Promise<void> => {
  try {
    // 会员数量（分页接口带 total）
    const memberRes = await getMemberList({ page: 1, pageSize: 1 })
    const memberTotal = memberRes?.code === 200 ? (memberRes.data?.total || 0) : 0

    // 会员等级数量（非分页数组）
    const levelRes = await getMemberLevelList({})
    const levels = levelRes?.code === 200 ? (Array.isArray(levelRes.data) ? levelRes.data : (levelRes.data?.list || [])) : []
    const levelTotal = levels.length

    // 未读通知数量（store 内获取总数）
    await notificationStore.fetchUnreadCount()
    const unread = notificationStore.unreadCount

    // 我的信息（显示昵称或用户名）
    const me = authStore.userInfo
    const meText = me?.nickname || me?.username || '未登录'

    stats.value = [
      { title: '会员数量', value: memberTotal, icon: User, color: '#409eff' },
      { title: '会员等级', value: levelTotal, icon: Document, color: '#67c23a' },
      { title: '未读通知', value: unread, icon: Message, color: '#e6a23c' },
      { title: '我的信息', value: meText, icon: DataAnalysis, color: '#f56c6c' }
    ]
  } catch (e) {
    // 忽略错误，避免阻塞页面
  }
}

// 加载最近通知作为最近活动
const loadRecentActivities = async (): Promise<void> => {
  try {
    const res = await getMyNotificationList({ page: 1, pageSize: 5, unread: false })
    if (res.code === 200 && res.data) {
      const list = res.data.list || []
      activities.value = list.map((n: any, idx: number) => ({
        id: n.id || idx,
        title: n.title,
        content: n.content,
        time: new Date(n.pushed_at || n.created_at).toLocaleString('zh-CN', { hour12: false })
      }))
    }
  } catch (e) {
    activities.value = []
  }
}

onMounted(async (): Promise<void> => {
  await loadStats()
  await loadRecentActivities()
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  .stat-card {
    margin-bottom: 20px;
    
    .stat-content {
      display: flex;
      align-items: center;
      
      .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        margin-right: 16px;
      }
      
      .stat-info {
        flex: 1;
        
        .stat-value {
          font-size: 24px;
          font-weight: 700;
          color: #333;
          margin-bottom: 4px;
        }
        
        .stat-title {
          font-size: 14px;
          color: #999;
        }
      }
    }
  }
  
  .card-header {
    font-weight: 600;
    font-size: 16px;
  }
  
  .quick-actions {
    display: flex;
    flex-direction: column;
    gap: 12px;
    
    .action-button {
      width: 100%;
      justify-content: flex-start;
    }
  }
}
</style>

